<template>
  <div class="ts-img-upload">
    <el-upload
      action="#"
      :file-list="fileList"
      :limit="limit"
      :class="{
        hide: this.fileList.length >= this.limit,
        'is-disabled': inputDisabled,
      }"
      :before-upload="onBeforeUpload"
      :before-remove="onBeforeRemove"
      :on-remove="onRemove"
      :on-error="onUploadError"
      :on-exceed="onExceed"
      :on-success="onUploadSuccess"
      :show-file-list="false"
      :http-request="onHttpRequest"
    >
      <el-button size="small" type="primary">上传文件</el-button>
      <div slot="tip" class="el-upload__tip">
        支持扩展名: .rar .zip .doc .docx .pdf
      </div>
    </el-upload>
    <div>
      <ul class="el-upload-list el-upload-list--text">
        <li
          tabindex="0"
          v-for="item in fileList"
          :key="item.id"
          class="el-upload-list__item is-success"
        >
          <!---->
          <el-button
            type="text"
            @click="onDownload(item)"
            class="el-upload-list__item-name"
          >
            <i class="el-icon-document"></i>{{ item.attachmentName }}
          </el-button>
          <label class="el-upload-list__item-status-label">
            <i class="el-icon-upload-success el-icon-circle-check"></i>
          </label>
          <i class="el-icon-close" @click="onBeforeRemove(item)"></i>
          <i class="el-icon-close-tip"></i
          ><!----><!---->
        </li>
      </ul>
      <!--      <a class="el-upload-list__item-name"  :href="item.url" v-for="item in fileList" :key="item.fileId" ><i class="el-icon-document"></i>-->
      <!--        {{ item.name }}-->
      <!--      </a>-->
    </div>
  </div>
</template>

<script lang="jsx">
import { uploadFile, downloadAttachment } from "../../api/index.js";
import { showError, showLoading, clearLoading } from "../../utils/message.js";
export default {
  name: "TsUpload",
  props: {
    value: {
      type: [String, Object, Array],
      // default: 'https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100'
    },
    limit: Number,
    // 大小限制(MB)
    fileSize: {
      type: Number,
      default: 5,
    },
    // 文件类型, 例如['png', 'jpg', 'jpeg']
    fileType: {
      type: Array,
      default: () => ["rar", "zip", "doc", "docx", "pdf"],
    },
    // 是否显示提示
    isShowTip: {
      type: Boolean,
      default: true,
    },
    addIconClass: {
      type: String,
      default: "el-icon-plus",
    },
    imgerror: [String, Object],
    disabled: Boolean,
  },
  components: {},
  data() {
    return {
      hideUpload: false,
      fileList: [],
    };
  },
  inject: {
    isFormGenerator: {
      type: Boolean,
      default: false,
    },
    elForm: {
      default: "",
    },
  },
  watch: {
    "fileList.length"(val) {
      this.updateValue()
    },
    value: {
      handler(val) {
        // console.log("val", val);
        if (val) {
          // 首先将值转为数组
          const list = Array.isArray(val) ? val : []
          this.fileList = list
        } else {
          this.fileList = [];
        }
      },
      deep: true,
      immediate: true,
    },
  },
  computed: {
    inputDisabled() {
      return this.disabled || (this.elForm || {}).disabled;
    },
    // 是否显示提示
    showTip() {
      return this.isShowTip && (this.fileType || this.fileSize);
    },
  },
  created() {},
  mounted() {},
  methods: {
    updateValue(){
      let value = this.fileList.map((item) => {
        let o = {...item}
        delete o.url
        return o
      });
      this.$emit("input", value);
    },
    async onHttpRequest({ file }){
      try {
        console.log("file", file);
        showLoading();
        let res = await uploadFile(file);
        this.onUploadSuccess(res);
      } catch (error) {
        console.error(error);
        showError("上传失败");
      }
    },
    async onBeforeRemove(file, fileList) {
      return this.$confirm("确认删除?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        // 用户点击了确定按钮后的操作
        // 可以在这里编写确认按钮被点击后的逻辑
        this.onRemove(file); // 例如，调用删除数据的方法
      }).catch(() => {
        // 用户点击了取消按钮后的操作
        // 可以在这里编写取消按钮被点击后的逻辑，或者不进行任何操作
      });
    },
    async onRemove(file, fileList) {
      // console.log('onRemove', file, fileList)
      let index = this.fileList.findIndex((t) => t.uid === file.uid);
      if (index > -1) {
        this.fileList.splice(index, 1);
        // let value = this.fileList.map((item) => item.url);
        // this.$emit("input", value.length === 1 ? value[0] : value);
        this.updateValue()
      }
    },
    // 上传成功回调
    onUploadSuccess(res) {
      let { data } = res;
      const row = data[0]
      this.fileList.push(row);
      clearLoading();
      this.updateValue()
    },
    // 上传前loading加载
    onBeforeUpload(file) {
      let isImg = false;
      if (this.fileType.length) {
        let fileExtension = "";
        if (file.name.lastIndexOf(".") > -1) {
          fileExtension = file.name.slice(file.name.lastIndexOf(".") + 1);
        }
        console.log(fileExtension);
        isImg = this.fileType.some((type) => {
          if (file.type.indexOf(type) > -1) return true;
          if (fileExtension && fileExtension.indexOf(type) > -1) return true;
          return false;
        });
      } else {
        isImg = file.type.indexOf("image") > -1;
      }

      if (!isImg) {
        showError(
          `文件格式不正确, 请上传${this.fileType.join("/")}图片格式文件!`
        );
        return false;
      }
      if (this.fileSize) {
        const isLt = file.size / 1024 / 1024 < this.fileSize;
        if (!isLt) {
          showError(`上传图片大小不能超过 ${this.fileSize} MB!`);
          return false;
        }
      }
      this.loading = this.$loading({
        lock: true,
        text: "上传中",
        background: "rgba(0, 0, 0, 0.7)",
      });
    },
    // 上传失败
    onUploadError() {
      showError("上传失败");
      this.loading.close();
    },
    // 文件个数超出
    onExceed() {
      showError(`上传文件数量不能超过 ${this.limit} 个!`);
    },
    onDownload(item){
      downloadAttachment(item)
    }
  },
};
</script>

<style lang="scss" scoped>
// .el-upload--picture-card 控制加号部分
::v-deep.hide .el-upload--picture-card,
::v-deep.is-disabled .el-upload--picture-card {
  display: none;
}
// 去掉动画效果
::v-deep .el-list-enter-active,
::v-deep .el-list-leave-active {
  transition: all 0s;
}

::v-deep .el-list-enter,
.el-list-leave-active {
  opacity: 0;
  transform: translateY(0);
}

::v-deep .el-upload--picture-card {
  margin: 0 8px 8px 0;
}
::v-deep .el-upload-list--picture-card .el-upload-list__item {
  overflow: visible;
}

//.ts-img-upload > div {
//  display: flex;
//  flex-direction: row-reverse;
//  justify-content: flex-end;
//}
//.el-upload__tip {
//  flex-direction: row !important;
//  justify-content: flex-start !important;
//}
</style>
<style lang="scss">
.ts-img-upload {
  .el-icon-circle-close {
    font-size: 18px;
    position: absolute;
    top: -10px;
    right: -10px;
    background: #fff;
  }
}
.is-mobile {
  .ts-img-upload {
    .el-upload-list--picture-card .el-upload-list__item,
    .el-upload--picture-card {
      width: 65px;
      height: 65px;
    }
    .el-upload--picture-card {
      line-height: 76px;
    }
    .el-icon-circle-close {
      font-size: 14px;
      top: -6px;
      right: -8px;
    }
  }
}
</style>
